package com.eascs.sqlfilter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.dao.SqlFilter;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.service.sys.SysOrgService;

/**
 * 数据权限过滤器
 * 
 * @author user
 *
 */
@Component
public class DataPermissionFilter implements SqlFilter {
	/** 权限关键字 */
	/// **DATA_PERMISSION(OL.LTD)**/
	private static final String DATA_PERMISSION_KEY = "DATA_PERMISSION";
	private static final String SQL_PATTERN_STR = "^.*\\/\\*\\*DATA_PERMISSION(\\([a-zA-Z\\.\\_]+\\))\\*\\*\\/.*$";
	public static final Pattern SQL_PATTERN = Pattern.compile(SQL_PATTERN_STR);

	@Reference
	private SysOrgService sysOrgService;

	@Override
	public String filterSql(String sql) {
		User user = UserHolder.getUser();
		if (StringUtils.contains(sql, DATA_PERMISSION_KEY)) {
			Matcher mather = SQL_PATTERN.matcher(sql);
			if (mather.matches()) {
				String group1 = mather.group(1);
				String colum = StringUtils.substringBetween(group1, "(", ")");
				String permissionStr = StringUtils.replace(user.getDataPermissionStr(), "/**PERMISSION_COLUM**/",
						colum);
				String sqlStr = StringUtils.replace(sql, "/**DATA_PERMISSION" + group1 + "**/", permissionStr);
				return sqlStr;
			}

		}
		return sql;
	}

	public static void main(String[] args) {
		String str = " SELECT DISTINCT * FROM (SELECT OL.BILLCODE,OL.CUSTOMERCODE||'-'||OL.CUSTOMERNAME, (SELECT HU.UNITCODE||'-'||HU.NAMECN AS NAMECN FROM EADB.HR_UNITS HU WHERE /**DATA_PERMISSION(HU.UNITNO)**/ HU.UNITNO = OL.LTD) NAMECN,ORF.LOANERNAME,(SELECT PDD.ITEMNAME FROM EADB.PUB_DDITEM PDD JOIN EADB.PUB_DATADICTIONARY PD ON PDD.DDNO=PD.DDNO  WHERE PD.DDCODE='OTOREPAYMENTWAY' AND OL.REPAYMENTWAY = PDD.ITEMCODE) ITEMNAME,  OL.LOANRATE*100,OL.LOANTERM,OL.LOANAMOUNT,ORFU.BANKLOANAMOUNT,OL.OPERATORNAME  FROM EADB.O2O_LOANAPPLY OL JOIN EADB.O2O_REFUND ORF ON OL.BILLCODE=ORF.LOADAPPLYCODE JOIN EADB.O2O_REFUNDLINE ORFL ON ORFL.REFUNDNO = ORF.REFUNDNO  LEFT JOIN EADB.O2O_REFUND ORFU ON ORFU.LOADAPPLYCODE = OL.BILLCODE WHERE ORFU.ISLOCK='N' AND ORFU.BANKREFUNDCODE <> 'GACZ') T WHERE 1=1  ORDER BY T.BILLCODE DESC ";
		Matcher mather = SQL_PATTERN.matcher(str);
		if (mather.matches()) {
			System.out.println(mather.group(1));
			String sqlStr = StringUtils.replace(str, "/**DATA_PERMISSION" + mather.group(1) + "**/", "xxxxx");
			System.out.println(sqlStr);
		}
	}
}
